# _*_ coding:utf-8 _*_
import os
import sys
import time
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import configparser
from API.config import setting
from API.lib.newreport import new_report
from API.lib.gethtml import get_htmlvalues

sys.path.append(os.path.dirname(os.path.dirname(__file__)))  # window环境适配的代码


# sys.path.append(os.path.abspath('..'))# linux环境适配的代码
def send_mail(file_new):
    """
    定义发送邮件
    :param file_new:
    :return: 成功：打印发送邮箱成功；失败：返回失败信息
    报告中测试用例名称需要修改ddt.py获取表格中的case_name显示
    """
    # 获取正文
    f = open(file_new, 'rb')
    mail_body = f.read()
    f.close()
    # 发送附件
    con = configparser.ConfigParser()
    con.read(setting.Test_Config, encoding='UTF-8')
    # 读取已生成的报告文件
    report = new_report(setting.Test_Report)
    sendfile = open(report, 'rb').read()
    # --------- 读取config.ini配置文件 ---------------
    Hoster = con.get("user", "HOST_SERVER")
    Sender = con.get("user", "FROM")
    Receiver = con.get("user", "TO")
    titles = get_htmlvalues(file_new)
    # 将字符串变成列表类型，同时发送多人
    if '[' in Receiver:
        receiver = eval(Receiver)
    else:
        receiver = Receiver
    User = con.get("user", "user")
    Pwd = con.get("user", "password")
    Subject = "【接口测试】" + titles + ' ' + con.get("user", "SUBJECT")
    # 邮件标题、正文内容
    att = MIMEText(sendfile, 'base64', 'utf-8')
    att["Content-Type"] = 'application/octet-stream'
    att.add_header("Content-Disposition", "attachment",
                   filename=("gbk", "", time.strftime("%Y-%m-%d %H_%M_%S") + "report.html"))
    msg = MIMEMultipart('related')
    msg.attach(att)
    msgtext = MIMEText(mail_body, 'html', 'utf-8')
    msg.attach(msgtext)
    msg['Subject'] = Subject
    msg['From'] = Sender
    msg['To'] = ''.join(receiver)
    # 发送邮件连接
    try:
        # server = smtplib.SMTP()
        server = smtplib.SMTP_SSL(Hoster, port=465)
        # server.set_debuglevel(1)  # 设置输出debug调试信息，默认不输出-------关闭调试输出（控制台打印）
        # server.connect(Hoster)
        # server.ehlo()# 使用ehlo指令像ESMTP（SMTP扩展）确认你的身份
        # server.starttls()# 使SMTP连接运行在TLS模式，所有的SMTP指令都会被加密
        server.login(User, Pwd)
        server.sendmail(Sender, receiver, msg.as_string())
        server.quit()
        print("邮件发送成功！")
    except Exception as e:
        print("失败: " + str(e))

# 调试连接邮件发送是否成功
# import smtplib
#
# def test_smtp_connection():
#     try:
#         server = smtplib.SMTP_SSL('smtp.qiye.aliyun.com', 465)
#         server.set_debuglevel(1)
#         server.login('xiexuexing@linghit.com', 'A7HqOdhbszHyNuCO')
#         print("SMTP连接成功！")
#         server.quit()
#     except Exception as e:
#         print(f"连接失败: {e}")
#
# test_smtp_connection()